﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZ;
using DAL;
namespace SinhNhat.admin.menu
{
    public partial class Menu : System.Web.UI.Page
    {
        private static bool flag_edit = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && Request.QueryString["id"] != null)
            {
                string id = Request.QueryString["id"];
                var menu = from me in WebUtils.db.MENUs
                           where me.MenuID.ToString() == id
                           select me;

                this.MenuImage.Attributes["src"] = menu.FirstOrDefault<MENU>().Icon;
                this.ImageHidden.Value = menu.FirstOrDefault<MENU>().Icon;
                name.Value = menu.FirstOrDefault().MenuText;
                linkto.Value = menu.FirstOrDefault().Url;
                flag_edit = true;
                return;

            }

            if (IsPostBack)
            {

                MENU menu = new MENU();
                menu.MenuText = name.Value;
                menu.Url = linkto.Value;
                menu.Icon = this.ImageHidden.Value;
                if (flag_edit == false)
                {
                    menu.MenuID = Guid.NewGuid(); 
                    WebUtils.db.MENUs.InsertOnSubmit(menu);
                }
                else
                {
                    MENU men = WebUtils.db.MENUs.Single(p => p.MenuID.ToString() == Request.QueryString["id"]);
                    men.MenuText = menu.MenuText;
                    men.Url = menu.Url;
                    men.Icon = menu.Icon;
                }

                try
                {
                    WebUtils.db.SubmitChanges();
                    if (flag_edit == false) Response.Redirect(Request.Url.AbsoluteUri);
                    else
                        ShowMessage("Success. Let Continue", "");
                    return;
                }
                catch (System.Exception ex)
                {
                    ShowMessage("Fail. Please Try Again", "");

                }
            }
            flag_edit = false;

        }
        void ShowMessage(string mTextMsg, string mControlFocus)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("");
            string s = Request.Url.AbsoluteUri;
            sb.Append("<script language=\"JavaScript\">");
            if (mTextMsg != "") sb.Append("  alert('" + mTextMsg + "');");
            if (mControlFocus != "") sb.Append("document.forms[0].item('" + mControlFocus + "').focus();");
            sb.Append("</script>");
            if (!IsStartupScriptRegistered("setFocus")) RegisterStartupScript("setFocus", sb.ToString());
        }
    }
}